<template>
  <view class="word-match-game">
    <!-- 游戏状态提示 -->
    <view v-if="matchedPairs<1" class="game-status">
      <text class="status-text">点击匹配的中英文单词对</text>
      <text class="pairs-text">已匹配: {{ matchedPairs }}/{{ totalPairs }}</text>
    </view>

    <!-- 游戏棋盘 - 所有卡片都显示内容 -->
    <view class="game-board">
      <view
          v-for="(card, index) in cards"
          :key="index"
          class="card"
          :class="getCardClass(card)"
          @click="selectCard(card)"
      >
        <view class="card-content">
          <text class="card-text">{{ card.content }}</text>
          <text class="card-type">{{ card.type === 'english' ? 'EN' : 'CN' }}</text>
        </view>

        <!-- 匹配成功效果 -->
        <view v-if="card.isMatched" class="match-effect">✓</view>
      </view>
    </view>

    <!-- 游戏统计信息 -->
    <view class="game-header">
      <view class="score-info">
        <text class="score-label">分数</text>
        <text class="score-value">{{ (matchedPairs / totalPairs * 100).toFixed(2) }}</text>
      </view>
      <view class="error-info">
        <text class="error-label">错误</text>
        <text class="error-value">{{ errors }}</text>
      </view>
      <view v-if="matchedPairs > 0" class="level-info">
        <text class="pairs-text">已匹配: {{ matchedPairs }}/{{ totalPairs }}</text>
      </view>
    </view>

    <!-- 游戏控制 -->
    <view class="game-controls">
      <button class="control-btn hint-btn" @click="showHint" :disabled="!hintsAvailable || selectedCards.length > 0">
        <text class="btn-icon">💡</text>
        <text class="btn-text">提示 ({{ hintsAvailable }})</text>
      </button>

      <button class="control-btn shuffle-btn" @click="shuffleCards" :disabled="selectedCards.length > 0">
        <text class="btn-icon">🔀</text>
        <text class="btn-text">重新排列</text>
      </button>

      <button class="control-btn reset-btn" @click="resetSelection" :disabled="selectedCards.length === 0">
        <text class="btn-icon">↶</text>
        <text class="btn-text">取消选择</text>
      </button>
    </view>

    <!-- 游戏结果弹窗 -->
    <view v-if="showResult" class="result-modal">
      <view class="result-content">
        <text class="result-title">{{ gameResult === 'win' ? '🎉 恭喜过关！' : '😔 游戏结束' }}</text>

        <view class="result-stats">
          <view class="stat-item">
            <text class="stat-label">得分</text>
            <text class="stat-value">{{ (matchedPairs / totalPairs * 100).toFixed(2) }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">用时</text>
            <text class="stat-value">{{ formatTime(timeUsed) }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">错误次数</text>
            <text class="stat-value">{{ errors }}</text>
          </view>
        </view>

        <view class="result-actions">
          <button class="result-btn restart-btn" @click="restartGame">
            <text>再玩一次</text>
          </button>
          <!--          <button class="result-btn next-btn" @click="nextLevel" v-if="gameResult === 'win'">
                      <text>下一关</text>
                    </button>-->
          <button class="result-btn exit-btn" @click="exitGame">
            <text>退出</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 匹配成功效果 -->
    <view v-if="showMatchEffect" class="match-success-effect">
      <text class="match-text">🎯 匹配成功！+{{ matchScore }}分</text>
    </view>

    <!-- 错误提示 -->
    <view v-if="showErrorEffect" class="error-effect">
      <text class="error-text">❌ 匹配错误！错误次数: {{ errors }}</text>
    </view>
  </view>
</template>

<script>
import {getWordListByCourseId} from "../../../api/wordSystemCourse";
import AudioCacheUtil from "../../../utils/AudioCacheUtil";

export default {
  name: "WordMatchGame",
  data() {
    return {
      // 游戏状态
      maxLevel: 3,
      errors: 0,
      timeUsed: 0,
      isPaused: false,
      gameStarted: false,
      showResult: false,
      gameResult: '', // 'win' or 'lose'

      // 卡片数据
      cards: [],
      cardsBackup: [],
      selectedCards: [],
      matchedPairs: 0,
      totalPairs: 0,

      // 提示系统
      hintsAvailable: 3,
      showHintEffect: false,
      hintPair: {},

      // 效果显示
      showMatchEffect: false,
      showErrorEffect: false,
      matchScore: 0,

      // 游戏计时器
      gameTimer: null,

      wordPairs: []
    };
  },

  onLoad() {
    this.initGame();
  },

  onUnload() {
    this.stopGameTimer();
  },

  methods: {
    // 初始化游戏
    async initGame() {
      this.wordPairs = await getWordListByCourseId({courseId: this.$route.query.courseId})
      this.wordPairs.forEach(pair => {
        pair.chinese = pair.wordMeaning
        pair.english = pair.wordFullSpell || pair.fullSpell
      })
      // 生成卡片
      this.generateCards();
      // 游戏计时器
      this.startGameTimer();
      this.gameStarted = true;
    },

    // 生成卡片
    generateCards() {
      this.cards = [];
      this.cardsBackup = [];
      this.selectedCards = [];
      this.matchedPairs = 0;

      // 获取当前关卡的单词对
      const allPairs = this.wordPairs
      const pairs = this.shuffleArray(allPairs)
      this.totalPairs = pairs.length;

      // 为每个单词对生成英文和中文卡片
      pairs.forEach(pair => {
        // 英文卡片
        this.cardsBackup.push({
          id: `${pair.english}-en`,
          content: pair.english,
          pairId: pair.english,
          type: 'english',
          isMatched: false
        });

        // 中文卡片
        this.cardsBackup.push({
          id: `${pair.english}-cn`,
          content: pair.chinese,
          pairId: pair.english,
          type: 'chinese',
          isMatched: false
        });
      });

      // 洗牌
      this.shuffleCards();

      this.refreshCards(6)
    },

    refreshCards(wordNums) {
      if (this.cardsBackup.length > 0) {
        const addCards = this.cardsBackup.splice(0, wordNums * 2)
        this.cards.push(...addCards)
        this.shuffleCards();
      }
    },

    // 洗牌
    shuffleCards() {
      this.cards = this.shuffleArray(this.cards);
    },

    // 选择卡片
    selectCard(card) {
      if (this.isPaused || this.showResult) return;
      if (card.isMatched) return;
      if (this.selectedCards.includes(card)) {
        this.resetSelection()
        return;
      }
      if (this.selectedCards.length >= 2) return;

      // 检查是否选择了同类型的卡片
      if (this.selectedCards.length === 1) {
        const firstCard = this.selectedCards[0];
        if (firstCard.type === card.type) {
          uni.showToast({
            title: '请选择另一种语言',
            icon: 'none',
            duration: 1000
          });
          return;
        }
      }

      if (card.type === 'chinese') {
        this.playZh(card.content)
      } else {
        this.playEn(card.content)
      }

      // 添加选中效果
      this.selectedCards.push(card);

      // 振动反馈
      uni.vibrateShort();

      // 如果选中了两张卡片，检查是否匹配
      if (this.selectedCards.length === 2) {
        setTimeout(() => {
          this.checkMatch();
        }, 300);
      }
    },

    // 检查卡片是否匹配
    checkMatch() {
      const [card1, card2] = this.selectedCards;

      // 检查是否是同一对卡片（相同的pairId）且一个是英文一个是中文
      if (card1.pairId === card2.pairId && card1.type !== card2.type) {
        this.handleMatchSuccess(card1, card2);
      } else {
        this.handleMatchFailure(card1, card2);
      }
    },

    playZh(text) {
      AudioCacheUtil.play(text, 'zh')
    },

    playEn(text) {
      AudioCacheUtil.play(text, 'en')
    },

    // 处理匹配成功
    handleMatchSuccess(card1, card2) {
      // 标记为已匹配
      card1.isMatched = true;
      card2.isMatched = true;

      // 计算得分（基于关卡）
      this.matchScore = (100 / this.wordPairs.length).toFixed(2)
      this.matchedPairs++;

      // 显示匹配成功效果
      this.showMatchEffect = true;
      setTimeout(() => {
        this.showMatchEffect = false;
      }, 1500);
      setTimeout(() => {
        // 删除匹配的卡片
        if (this.cardsBackup.length > 0) {
          this.cards.splice(this.cards.indexOf(card1), 1)
          this.cards.splice(this.cards.indexOf(card2), 1)

          // 刷新界面的单词
          this.refreshCards(1)
        }
      }, 300);

      // 清空选中卡片
      this.selectedCards = [];

      // 检查是否过关
      if (this.matchedPairs === this.totalPairs) {
        setTimeout(() => {
          this.endGame('win');
        }, 1000);
      }
    },

    // 处理匹配失败
    handleMatchFailure(card1, card2) {
      this.errors++;

      // 显示错误效果
      this.showErrorEffect = true;
      setTimeout(() => {
        this.showErrorEffect = false;
      }, 1500);

      // 清空选中卡片
      setTimeout(() => {
        this.selectedCards = [];
      }, 1000);
    },

    // 重置选择
    resetSelection() {
      this.selectedCards = [];
    },

    // 获取卡片样式类
    getCardClass(card) {
      return {
        'matched': card.isMatched,
        'selected': this.selectedCards.includes(card),
        'english': card.type === 'english',
        'chinese': card.type === 'chinese'
      };
    },

    // 提示功能
    showHint() {
      if (this.hintsAvailable <= 0) return;
      if (this.selectedCards.length > 0) return;

      // 找到第一个未匹配的单词对
      const unmatchedCards = this.cards.filter(card => !card.isMatched);
      if (unmatchedCards.length === 0) return;

      const firstCard = unmatchedCards[0];
      const pairId = firstCard.pairId;
      const pairCards = this.cards.filter(card => card.pairId === pairId && !card.isMatched);

      if (pairCards.length === 2) {
        this.hintsAvailable--;

        // 高亮显示对应的两张卡片
        pairCards.forEach(card => {
          // 添加临时高亮效果
          this.$set(card, 'isHinted', true);
          setTimeout(() => {
            this.$set(card, 'isHinted', false);
          }, 2000);
        });

        uni.showToast({
          title: `提示: ${pairCards.find(c => c.type === 'english').content} - ${pairCards.find(c => c.type === 'chinese').content}`,
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 游戏计时器
    startGameTimer() {
      this.gameTimer = setInterval(() => {
        if (!this.isPaused && this.gameStarted && !this.showResult) {
          this.timeUsed++;
        }
      }, 1000);
    },

    stopGameTimer() {
      if (this.gameTimer) {
        clearInterval(this.gameTimer);
      }
    },

    // 结束游戏
    endGame(result) {
      this.gameResult = result;
      this.showResult = true;
      this.stopGameTimer();
    },

    // 重新开始游戏
    restartGame() {
      this.showResult = false;
      this.errors = 0;
      this.timeUsed = 0;
      this.hintsAvailable = 3;
      this.initGame();
    },

    // 退出游戏
    exitGame() {
      uni.navigateBack();
    },

    // 工具函数
    shuffleArray(array) {
      const newArray = [...array];
      for (let i = newArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
      }
      return newArray;
    },

    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.word-match-game {
  padding: 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

/* 游戏头部 */
.game-header {
  display: flex;
  justify-content: space-between;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.score-info, .level-info, .error-info {
  display: flex;
  gap: 8rpx;
}

.score-label, .level-label, .error-label {
  font-size: 24rpx;
  color: #7f8c8d;
  margin-bottom: 8rpx;
}

.score-value, .level-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #2c3e50;
}

.error-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #e74c3c;
}

/* 游戏状态 */
.game-status {
  display: flex;
  justify-content: space-between;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.status-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #2c3e50;
  display: block;
  margin-bottom: 10rpx;
}

.pairs-text {
  font-size: 28rpx;
  color: #3498db;
}

/* 游戏棋盘 - 所有卡片都显示内容 */
.game-board {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.card {
  aspect-ratio: 4/2;
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 3rpx solid #e0e0e0;
}

.card.selected {
  transform: scale(1.05);
  border-width: 4rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.15);
}

.card.matched {
  opacity: 0.3;
  transform: scale(0.9);
}

.card.english {
  border-color: #3498db;
}

.card.english.selected {
  background: linear-gradient(135deg, #e3f2fd, #bbdefb);
  border-color: #1976d2;
}

.card.chinese {
  border-color: #e74c3c;
}

.card.chinese.selected {
  background: linear-gradient(135deg, #ffebee, #ffcdd2);
  border-color: #d32f2f;
}

.card.hinted {
  animation: hintPulse 2s ease-in-out;
}

.card-content {
  text-align: center;
}

.card-text {
  font-size: 36rpx;
  font-weight: bold;
  color: #2c3e50;
  display: block;
  margin-bottom: 8rpx;
}

.card-type {
  font-size: 20rpx;
  color: #7f8c8d;
  background: #f0f0f0;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.match-effect {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 60rpx;
  color: #27ae60;
  animation: matchPulse 0.6s ease-in-out;
}

@keyframes matchPulse {
  0% {
    transform: translate(-50%, -50%) scale(0);
    opacity: 0;
  }
  50% {
    transform: translate(-50%, -50%) scale(1.2);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
}

@keyframes hintPulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
    box-shadow: 0 0 30rpx gold;
  }
  100% {
    transform: scale(1);
  }
}

/* 游戏控制 */
.game-controls {
  display: flex;
  gap: 16rpx;
}

.control-btn {
  flex: 1;
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  border: none;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.control-btn:disabled {
  opacity: 0.6;
}

.hint-btn {
  background: linear-gradient(135deg, #f39c12, #d35400);
}

.shuffle-btn {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
}

.reset-btn {
  background: linear-gradient(135deg, #95a5a6, #7f8c8d);
}

.btn-icon {
  font-size: 40rpx;
}

.btn-text {
  font-size: 24rpx;
}

/* 结果弹窗 */
.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.result-content {
  background: white;
  border-radius: 30rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  width: 80%;
}

.result-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 40rpx;
  display: block;
}

.result-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 24rpx;
  color: #7f8c8d;
  margin-bottom: 8rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #3498db;
}

.result-actions {
  display: flex;
  gap: 20rpx;
}

.result-btn {
  width: 100%;
  flex: 1;
  padding: 20rpx;
  border: none;
  border-radius: 16rpx;
  color: white;
  font-size: 28rpx;
}

.restart-btn {
  background: #3498db;
}

.next-btn {
  background: #27ae60;
}

.exit-btn {
  background: #95a5a6;
}

/* 效果提示 */
.match-success-effect {
  position: fixed;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(39, 174, 96, 0.95);
  color: white;
  padding: 30rpx 60rpx;
  border-radius: 50rpx;
  font-size: 36rpx;
  font-weight: bold;
  z-index: 999;
  animation: matchSuccess 1.5s ease-in-out;
}

.error-effect {
  position: fixed;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(231, 76, 60, 0.95);
  color: white;
  padding: 30rpx 60rpx;
  border-radius: 50rpx;
  font-size: 36rpx;
  font-weight: bold;
  z-index: 999;
  animation: errorShake 1.5s ease-in-out;
}

@keyframes matchSuccess {
  0% {
    transform: translate(-50%, -50%) scale(0.8);
    opacity: 0;
  }
  50% {
    transform: translate(-50%, -50%) scale(1.1);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0;
  }
}

@keyframes errorShake {
  0%, 100% {
    transform: translate(-50%, -50%);
  }
  25% {
    transform: translate(-55%, -50%);
  }
  75% {
    transform: translate(-45%, -50%);
  }
}

/* 响应式设计 */
@media (max-width: 750px) {
  .game-header {
    gap: 20rpx;
  }

  .game-board {
    grid-template-columns: repeat(2, 1fr);
  }

  .result-actions {
    flex-direction: column;
  }
}
</style>
